package com.qianlima.upload.infrastructure.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @description: hash算法
 * @author：allms
 * @date: 2023/3/24 13:11
 */
public class HashUtils {

    private final static String MD5 = "MD5";
    private final static String SHA256 = "SHA-256";
    private final static String HEX = "0123456789ABCDEF";

    private static String hash(String input, String algorithm) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String sha256(String input) {
        return hash(input, SHA256);
    }

    public static String md5(String input) {
        return hash(input, MD5);
    }
}
